package com.goldenautumn.prefabricate.activity.mall

import android.animation.Animator
import android.animation.ValueAnimator
import android.graphics.Path
import android.graphics.PathMeasure
import android.net.http.SslError
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.webkit.JsResult
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.VibrateUtils
import com.goldenautumn.prefabricate.MainActivity
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.cart.RecommendedGoodsAdapter
import com.goldenautumn.prefabricate.activity.mall.adapter.CenterLayoutManager
import com.goldenautumn.prefabricate.activity.mall.adapter.GoodsSpecAdapter
import com.goldenautumn.prefabricate.activity.mall.adapter.ImageBannerAdapter
import com.goldenautumn.prefabricate.business.entity.GoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.GoodsSpecVo
import com.goldenautumn.prefabricate.business.entity.SearchParams
import com.goldenautumn.prefabricate.business.entity.SpecSelectInfo
import com.goldenautumn.prefabricate.business.mall.CarDataUiState
import com.goldenautumn.prefabricate.business.mall.GoodsInfoUiState
import com.goldenautumn.prefabricate.business.mall.MallViewModel
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.databinding.ActivityGoodsDetailsBinding
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.clickIsLogin
import com.goldenautumn.prefabricate.utils.loadImgUrl
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.gyf.immersionbar.ImmersionBar
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseActivity
import qncx.external.common.compat.gone
import qncx.external.common.compat.isVisible
import qncx.external.common.compat.visible
import qncx.external.common.compat.visibleOrInvisible
import qncx.external.common.utils.intent
import qncx.external.common.widget.dialog.LoadingDialog
import qncx.external.common.widget.shapeview.CircleImageView
import qncx.external.common.widget.shapeview.shape.ShapeButton


class GoodsDetailsActivity : BaseActivity<ActivityGoodsDetailsBinding>() {

    private val mMallModel by viewModels<MallViewModel>()

    private val mRecommendedAdapter by lazy {
        RecommendedGoodsAdapter()
    }

    val goodsID:Int?
        get() = intent.getIntExtra(BUSINESS_PAGE_DATA,0)

    var goodsInfoVO:GoodsInfoVO? = null

    var specInfo:Int? = null

    var specItems:MutableList<GoodsSpecVo>? = null

    val bannerAdapter = ImageBannerAdapter(arrayListOf())

    override fun getLayoutId(): Int = R.layout.activity_goods_details

    override suspend fun main() {
        ImmersionBar.setTitleBar(this, mBinding.toolbar)
        mBinding.toolbar.setNavigationOnClickListener { onBackPressedDispatcher.onBackPressed() }
        initWeb()
        mBinding.goodsBtn.setOnClickListener {
            var height = SizeUtils.getMeasuredHeight(mBinding.toolbar) + 20
            mBinding.scroller.scrollToChildWithOffset(mBinding.detailsPirce,height)
            setTabSelect(1)
        }
        mBinding.detailsBtn.setOnClickListener {
            var height = SizeUtils.getMeasuredHeight(mBinding.toolbar) + 20
            mBinding.scroller.scrollToChildWithOffset(mBinding.details,height)
            setTabSelect(2)
        }

//        mBinding.linearLayout.setOnClickListener {
//            var select = SpecSelectInfo(mSpecAdapter.selectPosition,mBinding.count.text.toString())
//            SpecDialog(mSpecAdapter.items,goodsInfoVO,select) {
//                mSpecAdapter.selectPosition = select.position
//                mSpecAdapter.notifyDataSetChanged()
//                var item  = if(it.position != -1) mSpecAdapter.getItem(it.position) else null
//                specInfo = item?.item_id
//                mBinding.spec.text = "${item?.spec_value}"
//                mBinding.count.text = "${select.count}"
//                mBinding.price.text = (String.format(getString(R.string.currency), "${item?.goods_price}"))
//            }.onShow(supportFragmentManager.beginTransaction())
//        }

        mBinding.scroller.setOnVerticalScrollChangeListener { v, scrollY, oldScrollY, scrollState ->
            if(scrollState == 0) bannerAdapter?.notifyItemRangeChanged(0, bannerAdapter.itemCount)
            var height = SizeUtils.getMeasuredHeight(mBinding.coverBanner) - SizeUtils.getMeasuredHeight(mBinding.toolbar) - 80
            if(scrollY > height) {
                mBinding.tabContent.visible()
                mBinding.icon.setImageResource(R.mipmap.ic_details_car_bark)
                mBinding.toolbar.setBackgroundColor(ContextCompat.getColor(this,R.color.white))
            } else {
                mBinding.tabContent.gone()
                mBinding.icon.setImageResource(R.mipmap.ic_details_car_white)
                mBinding.toolbar.setBackgroundColor(ContextCompat.getColor(this,
                    qncx.external.common.R.color.transparent))
            }
        }


        mBinding.recommendedRv.layoutManager = LinearLayoutManager(this,RecyclerView.HORIZONTAL,false)
        mBinding.recommendedRv.adapter = mRecommendedAdapter

        mBinding.htmlContent.webChromeClient = object :WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                // 在webView加载的过程中，用户滚动了webView内容，可能会使webView的显示与scrollerLayout断层，
                // 需要让scrollerLayout重新检查一下所有View的显示位置
                mBinding.scroller.checkLayoutChange()
            }
        }

        mBinding.addCarBtn.clickIsLogin {
            if(specInfo == null){
                onCenterToast(getString(R.string.please_select_spec))
                VibrateUtils.vibrate(50)
                mBinding.addCarBtn.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake_anim))
            } else if(specItems != null && specItems?.size != 0){
                var select = SpecSelectInfo(-1,mBinding.count.text.toString())
                SpecDialog(specItems!!,goodsInfoVO,select) {
                    var item  = if(it.position != -1) specItems?.get(it.position) else null
                    specInfo = item?.item_id
                    mBinding.count.text = "${select.count}"
                    mBinding.price.text = (String.format(getString(R.string.currency), "${item?.goods_price}"))

                    mLoading = LoadingDialog()
                    mLoading.onShow(supportFragmentManager.beginTransaction())
                    mMallModel.addCar("$goodsID",mBinding.count.text.toString(),"$specInfo")

                }.onShow(supportFragmentManager.beginTransaction())
            } else {
                mLoading = LoadingDialog()
                mLoading.onShow(supportFragmentManager.beginTransaction())
                mMallModel.addCar("$goodsID",mBinding.count.text.toString(),"$specInfo")
            }
        }

        mBinding.icon.clickIsLogin {
            SPUtils.getInstance().put("home",2)
            startActivity(MainActivity::class.intent)
        }

        mBinding.coverBanner.setAdapter(bannerAdapter)
            .addBannerLifecycleObserver(this) //添加生命周期观察者
            .setIndicator(CircleIndicator(this)) //设置指示器
            .setOnBannerListener { data, position ->
                LogUtils.d("position：$position")
            }.addOnPageChangeListener(object :OnPageChangeListener {
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

                }

                override fun onPageSelected(position: Int) {
                    mBinding.indicator.text = "${position + 1}/${mBinding.coverBanner.itemCount - 2}"
                }

                override fun onPageScrollStateChanged(state: Int) {

                }
            })

        var detailsTest = "<p><img src=\"http://oss.hnkzlin.com/mall/assets/微信图片_20231213124617.jpg\" /><img src=\"http://oss.hnkzlin.com/mall/assets/微信图片_20231213124607.jpg\" /><img src=\"http://oss.hnkzlin.com/mall/assets/微信图片_20231213124558.jpg\" /><img src=\"http://oss.hnkzlin.com/mall/assets/微信图片_20231213124550.jpg\" /><img src=\"http://oss.hnkzlin.com/mall/assets/微信图片_20231213124538.jpg\" /></p>"



        mBinding.goodsSub.setOnClickListener {
            var number = mBinding.count.text.toString().toInt()
            if(number != 1) {
                var count = number - 1
                var sub = "$count"
                mBinding.count.text = sub

            }
        }

        mBinding.goodsAdd.setOnClickListener {
            var number = mBinding.count.text.toString().toInt()
            var count = number + 1
            var add = "$count"
            mBinding.count.text = add

        }

        mRecommendedAdapter.setOnItemClickListener{adapter,_,position ->
            var item = adapter.getItem(position)
            startActivity(GoodsDetailsActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,item?.goods_id))
        }

        mMallModel.getCarList()
        mMallModel.getGoodsList(SearchParams())
        mMallModel.getGoodsDetails("$goodsID")

        while (isActive) {
            select {
                mMallModel.loading.onReceive {
                    when(it) {
                        is LoadingUiState.LoadingUI -> {
                            if(!it.isShow) mBinding.loading.gone()
                            if(mLoading.isVisible && !it.isShow) mLoading.dismiss()
                            LogUtils.d("加载状态=${it.isShow}")
                        }
                        else -> {}
                    }
                }
                mMallModel.goodsDetailsRequests.onReceive {
                    when(it) {
                        is GoodsInfoUiState.GoodsDetails -> {
                            goodsInfoVO = it.goods
                            var bannerImg = ArrayList<String>()
                            it.goods?.image?.forEach { bannerImg.add("${it.file_path}") }
                            bannerAdapter.setDatas(bannerImg)
                            mBinding.coverBanner.setCurrentItem(1,false)
                            mBinding.coverBanner.setCurrentItem(0,false)
                            mBinding.indicator.text = "1/${bannerImg.size}"

                            if(it.goods.goods_multi_spec != null && it.goods.goods_multi_spec != null && it.goods.goods_multi_spec?.spec_attr?.size != 0){
                                  specItems = it.goods.goods_multi_spec?.spec_attr?.get(0)?.spec_items
//                                mBinding.linearLayout.visible()
//                                mSpecAdapter.submitList(it.goods.goods_multi_spec?.spec_attr?.get(0)?.spec_items)
//                                if(mSpecAdapter.items.isNotEmpty()) {
//                                    mSpecAdapter.selectPosition = 0
//                                    mBinding.spec.text = "${mSpecAdapter.getItem(0)?.spec_value}"
//                                }
                            }

                            mBinding.price.text = (String.format(getString(R.string.currency), "${it.goods?.goods_sku?.goods_price}"))
                            specInfo = (it.goods?.goods_sku?.spec_sku_id ?: "0").toInt()

                            mBinding.title.text = "${it.goods?.goods_name}"
                            var content = "${it.goods?.content?.replace("<p>","")}".replace("</p>","")
                            mBinding.htmlContent.loadDataWithBaseURL(
                                null,
                                getHtmlData("<p>${content}</p>"),
                                "text/html",
                                "utf-8",
                                null
                            )
                            LogUtils.d("商品详情=${it.goods}")
                        }
                        is GoodsInfoUiState.GoodsList -> {
                            it.goodsList.shuffle()
                            mRecommendedAdapter.submitList(it.goodsList)
                        }
                        is GoodsInfoUiState.GoodsAddCar -> {
                            if(it.msg == null) {
                                addCard()
                                mMallModel.getCarList()
                            } else onCenterToast(it.msg ?: "")
                        }
                        else -> {}
                    }
                }
                mMallModel.carDataReq.onReceive {
                    when(it) {
                        is CarDataUiState.CarList -> {
                            mBinding.carCount.visibleOrInvisible(it.data?.size != 0)
                            mBinding.carCount.text = "${it.data?.size}"
                        }
                        else -> {

                        }
                    }
                }
            }
        }

    }

    fun setTabSelect(position:Int){
        if(position == 1) {
            mBinding.goodsBtn.setTextColor(ContextCompat.getColor(this,R.color.colorPrimary))
            mBinding.detailsBtn.setTextColor(ContextCompat.getColor(this,R.color.color_1D1F20))
            mBinding.goodsBtn.setCompoundDrawablesWithIntrinsicBounds(null, null, null, ContextCompat.getDrawable(this, R.mipmap.ic_tab_indicator))
            mBinding.detailsBtn.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        } else {
            mBinding.detailsBtn.setTextColor(ContextCompat.getColor(this,R.color.colorPrimary))
            mBinding.goodsBtn.setTextColor(ContextCompat.getColor(this,R.color.color_1D1F20))
            mBinding.detailsBtn.setCompoundDrawablesWithIntrinsicBounds(null, null, null, ContextCompat.getDrawable(this, R.mipmap.ic_tab_indicator))
            mBinding.goodsBtn.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        }
    }

    fun initWeb() {
        val webSettings: WebSettings = mBinding.htmlContent.settings
        webSettings.javaScriptEnabled = true //允许使用js
        webSettings.setSupportZoom(false)  //不支持屏幕缩放
        webSettings.builtInZoomControls = false
        webSettings.displayZoomControls = false  //不显示webview缩放按钮
        webSettings.blockNetworkImage = false
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        mBinding.htmlContent.webChromeClient = object : WebChromeClient() {
            //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
            override fun onJsAlert(webView: WebView, url: String, message: String, result: JsResult): Boolean {
                //注意:
                //必须要这一句代码:result.confirm()表示:
                //处理结果为确定状态同时唤醒WebCore线程
                //否则不能继续点击按钮
                result.confirm()
                return true
            }
        }

        mBinding.htmlContent.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                runOnUiThread {
                    //webview加载完成之后重新测量webview的高度
                    val params: ViewGroup.LayoutParams = mBinding.htmlContent.layoutParams
                    params.height = mBinding.htmlContent.contentHeight
                    mBinding.htmlContent.layoutParams = params
                }
            }

            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                handler?.proceed()
            }

        }
    }


    private fun getHtmlData(bodyHTML: String): String {
        val head = ("<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:100%; height:auto;};img{margin:0px;vertical-align:middle;};html{margin: 0px;padding: 0px;}</style>"
                + "</head>")
        return "<html>$head<body style=\"margin:0; padding:0;\">$bodyHTML</body></html>"
    }

    private var mPathMeasure: PathMeasure? = null

    private val mCurrentPosition = FloatArray(2)

    fun addCard(){
        var cover = CircleImageView(this)
        cover.loadImgUrl(goodsInfoVO?.goods_image)
        var lp = ConstraintLayout.LayoutParams(80,80)
        mBinding.layout.addView(cover, lp)

        val parentLocation = IntArray(2)
        mBinding.layout.getLocationInWindow(parentLocation)

        val startLoc = IntArray(2)
        mBinding.addCarBtn.getLocationInWindow(startLoc)

        val endLoc = IntArray(2)
        mBinding.icon.getLocationInWindow(endLoc)

        val startX: Int = startLoc[0] - parentLocation[0] + mBinding.addCarBtn.width / 2
        val startY: Int = startLoc[1] - parentLocation[1] + mBinding.addCarBtn.height / 2

        val toX: Int = endLoc[0] - parentLocation[0] + mBinding.icon.width / 5
        val toY = (endLoc[1] - parentLocation[1]).toFloat()

        val path = Path()
        path.moveTo(startX.toFloat(), startY.toFloat())
        path.quadTo(((startX + toX) / 2).toFloat(), startY.toFloat(), toX.toFloat(), toY)
        mPathMeasure = PathMeasure(path, false)

        val valueAnimator = ValueAnimator.ofFloat(0f, mPathMeasure?.length ?: 0f)
        valueAnimator.duration = 600
        valueAnimator.interpolator = LinearInterpolator()
        valueAnimator.addUpdateListener {
            val value = it.animatedValue as Float
            mPathMeasure?.getPosTan(value, mCurrentPosition, null)
            cover.translationX = mCurrentPosition[0]
            cover.translationY = mCurrentPosition[1]
        }
        valueAnimator.start()
        valueAnimator.addListener(object : Animator.AnimatorListener{
            override fun onAnimationStart(p0: Animator) {

            }

            override fun onAnimationEnd(p0: Animator) {
                mBinding.layout.removeView(cover)
            }

            override fun onAnimationCancel(p0: Animator) {

            }

            override fun onAnimationRepeat(p0: Animator) {

            }
        })
        onCenterToast(getString(R.string.added_cart))
    }

}